<template>
  <div style="height: 100%;padding: 15px 20px 15px 20px;">
    <div class="header">
      <el-button @click="scanToJpg">扫描仪</el-button>
      <el-button @click="submit">提交</el-button>
    </div>
    <div class="content">
      <div class="hoverDeleBtn" v-for="(item,index) in imageData" :key="`big${index}`">
        <div v-for="(innerItem,innerIndex) in item" :key="`smell${innerIndex}`">

          <template>
            <el-image v-if="innerItem.src!=''" :key="`smell${innerIndex}`" :src="innerItem.src"
                      fit="contain"></el-image>
            <div v-else class="el-image" style="display: flex;align-items: center;justify-content: center">
              <el-upload
                :action="baseUrl + '/common/upload'"
                :headers="{
                  Authorization: `Bearer  ${token}`,
                }"
                :limit="1"
                class="upload-demo"
                :before-upload="(file)=>onSuccess(response,innerItem,file)"
              >
<!--                :on-success="(response,file)=>onSuccess(response,innerItem,file)"-->
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </div>

          </template>


        </div>

        <div class="deletedBtn" >
          <i class="el-icon-remove-outline" @click="deleteList(item,index)"></i>
        </div>

      </div>
      <div class="addBtn">
          <i class="el-icon-circle-plus-outline" @click="addList"></i>
      </div>

    </div>
  </div>
</template>

<script>
// import scanner from '/public/static/scanner'
import {addPaperData, base64ToUrl} from "@/api/markingPapers";
import {mapGetters} from "vuex";

export default {
  data() {
    return {
      imageData: [],


    }
  },
  mounted() {

  },
  computed: {
    ...mapGetters(["baseUrl", "userId",'token']),
  },
  methods: {
    scanToJpg() {

      scanner.scan(this.displayImagesOnPage,
        {
          "output_settings":
            [
              {
                "type": "return-base64",
                "format": "jpg"
              }
            ]
        }
      );
    },
    displayImagesOnPage(successful, mesg, response) {
      if (!successful) { // On error
        console.error('Failed: ' + mesg);
        return;
      }

      if (successful && mesg != null && mesg.toLowerCase().indexOf('user cancel') >= 0) { // User canceled.
        console.info('User canceled');
        return;
      }

      var scannedImages = scanner.getScannedImages(response, true, false); // returns an array of ScannedImage
      console.log(scannedImages)
      // this.imageData = scannedImages
      this.imageData = []
      for (let i = 0; i < scannedImages.length; i += 2) {
        if (i + 1 < scannedImages.length) { // 确保不会越界
          let arr = [scannedImages[i], scannedImages[i + 1]]; // 使用 i + 1 而不是 i=1
          this.imageData.push(arr);
        } else if (i < scannedImages.length) { // 如果数组长度为奇数，处理最后一个元素
          let arr = [scannedImages[i], {src: ''}]; // 最后一个元素单独作为一对（或者可以省略这部分）
          this.imageData.push(arr);
        }
      }

    },
    submit() {
      if (this.imageData.length == 0) {
        this.$message({
          message: '请上传图片',
          type: 'warning'
        });
      }

      console.log()
      if(this.imageData[this.imageData.length-1][0].src==''){
        this.imageData.splice(this.imageData.length-1,1)
      }else if (this.imageData[this.imageData.length-1][1].src==''){
        this.imageData[this.imageData.length-1].splice(1,1)
      }


      this.$confirm('请确认图片数量及顺序', '提示', {
        confirmButtonText: '数据是正确的',
        cancelButtonText: '去确认',
        type: 'warning'
      }).then(() => {
        this.formSumbit()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });


    },
    async formSumbit() {
      for (const ele of this.imageData) {
        let obj = {
          answerPicture: null,
          questionPicture: null
        }

        for (var innerIndex = 0; innerIndex < ele.length; innerIndex += 2) {


          this.$message.info('共' + (ele.length) + '道试题，正在上传第' + (innerIndex + 1) + '道试题')


          if (innerIndex + 1 < ele.length) { // 确保不会越界
            let formData1 = new FormData()
            let formData2 = new FormData()
            formData1.append('base64', ele[innerIndex + 1].src.replace(/[\n\r]/g, ''))
            formData2.append('base64', ele[innerIndex].src.replace(/[\n\r]/g, ''))
            let res1 = await base64ToUrl(formData1)
            obj.answerPicture = res1.url
            let res2 = await base64ToUrl(formData2)
            obj.questionPicture = res2.url
            // this.imageData.push(arr);
          } else if (innerIndex < ele.length) { // 如果数组长度为奇数，处理最后一个元素

            let formData1 = new FormData()
            formData1.append('base64', ele[innerIndex].src.replace(/[\n\r]/g, ''))
            let res1 = await base64ToUrl(formData1)
            obj.questionPicture = res1.url
            // this.imageData.push(arr);
          }


        }

        console.log(obj,'第一')
        let abc = await addPaperData(obj)
        console.log(abc, 'abc')


      }
    },
    //缺页手动上传
   async onSuccess(res, item,file) {
      console.log(res, file)
      // item.src = res.url

      item.src=  await this.convertToBase64(file)
    },
    addList(){
      let arr=[
        {src:''},
        {src:''}
      ]
      this.imageData.push(arr)
    },
    //URL-BASE64
    convertToBase64(file) {


      if (!file) {
        alert('请选择一个图片文件');
        return;
      }


      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) =>{
          // e.target.result 包含完整的data URL，你可以通过split(',')来获取Base64编码部分
          const base64data = e.target.result.split(',')[1];
          console.log('data:'+file.type+';base64,'+ base64data,'base64data')
          resolve('data:'+file.type+';base64,'+ base64data)
          // return 'data:'+file.type+';base64,'+ base64data;
        };
      })

    },
    //删除行
    deleteList(item,index){
      this.imageData.splice(index,1)
    }


  }
}
</script>
<style lang="scss" scoped>
.header {
  height: 70px;
  display: flex;
  align-items: center;

  .el-button {
    background-color: #1890ff;
    color: #FFFFFF;
  }
}

.content {
  height: calc(100% - 70px);
  width: 100%;
  //display: flex;
  //align-content: flex-start;
  //flex-wrap: wrap;
  padding-left: 10px;

  > div {
    display: flex;

  }

  .el-image {
    width: 200px;
    height: 200px;
    margin-right: 10px;
    margin-bottom: 10px;
    border: 1px solid #e8e8e8;

  }
}

.addBtn{
  width: 410px;
  text-align: center;
  .el-icon-circle-plus-outline{
    font-size: 50px;
    margin: 0 auto;
    color: #409EFF;
  }
}
.deletedBtn{
  text-align: center;
  height: 200px;
  margin-left: 15px;
  line-height: 200px;
  display: none;
  .el-icon-remove-outline{
    font-size: 30px;
    margin: 0 auto;
    color: #F56C6C;
  }
}

.hoverDeleBtn:hover{
  .deletedBtn{
    display: block;
  }
}
</style>
